import requests
import time
from django.conf import settings

class BaiDuApi():
    API_KEY = "TrgdHVhSrvXU3X0I1396Krb9"
    SECRET_KEY = "dQiRsK2vQxIuHmLV95joRYqIaC21Ov1J"
    TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token"
    OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"

    def __init__(self):
        self._access_token = None
        self._token_expire = 0

    def get_access_token(self):
        now = time.time()
        if self._access_token and now < self._token_expire:
            return self._access_token
        params = {
            "grant_type": "client_credentials",
            "client_id": self.API_KEY,
            "client_secret": self.SECRET_KEY
        }
        resp = requests.post(self.TOKEN_URL, params=params).json()
        self._access_token = resp.get("access_token")
        # access_token 有效期一般为30天，这里取1天后过期，防止提前失效
        self._token_expire = now + 24*60*60
        return self._access_token

    def idcard_ocr(self, image_base64, id_card_side="front"):
        url = f"{self.OCR_URL}?access_token={self.get_access_token()}"
        payload = {
            'image': image_base64,
            'id_card_side': id_card_side,
            'detect_ps': 'false',
            'detect_risk': 'false',
            'detect_quality': 'false',
            'detect_photo': 'false',
            'detect_card': 'false',
            'detect_direction': 'false',
        }
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        response = requests.post(url, headers=headers, data=payload)
        return response.json()
